//
//  Statuses.swift
//  DSWeibo
//
//  Created by J on 16/4/18.
//  Copyright © 2016年 J. All rights reserved.
//

import UIKit
import SDWebImage.UIImageView_WebCache
class Statuses: NSObject {
    
    /// 用户名
//    var : String?
    /// 微博创建时间
    var created_at: String?{
        
        didSet{
             created_at = NSDate.dateWithStr(created_at!)
        }
        
    }
    /// 微博创建时间
    var id: Int = 0
    /// 微博ID
    var text: String?
    /// 微博来源   <a href="http://weibo.com/" rel="nofollow">周杰伦的iPhone 6 Plus</a>
    var source: String?{
        didSet{
            //1.截取自符串
            //1.1获取开始截取的位置
            //1.2获取截取的长度
//            //1.3截取自符串
            if let str = source  {
                if str == "" {//没有来源
                    return
                }
                
//                let range = str.rangeOfString("^>.*?<$", options: NSStringCompareOptions.RegularExpressionSearch, range:Range(start: 0,end:(str as NSString).length))
                
                let starLocation = (str as NSString).rangeOfString(">").location + 1
                let length = (str as NSString).rangeOfString("<", options: NSStringCompareOptions.BackwardsSearch).location - starLocation
                source = (str as NSString).substringWithRange(NSMakeRange(starLocation ,length))
            }

        }
    }
    
    /// 配图数组
    var pic_urls: [[String:AnyObject]]?{
        didSet{
            storePicURLS = [NSURL]()//初始化一个数组
            storeMiddlPicURLS = [NSURL]()//初始化一个数组

            for picDict in pic_urls! {//遍历取出所有图片地址
                if let urlStr = picDict["thumbnail_pic"] as? String{//自符串转换为URL保存到模型的数组中
                    storePicURLS?.append(NSURL(string: urlStr)!)
                    
                    //处理大图
                    let middleURLStr = urlStr.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
                    storeMiddlPicURLS?.append(NSURL(string: middleURLStr)!)//存储中等图片

                }
                
            }
        
        }
    }

    
    
    
    ///保存当前微博所有配图URL
    var storePicURLS: [NSURL]?
    var storeMiddlPicURLS:[NSURL]?//大图url
    //转发微博
    var retweeted_status: Statuses?
    
    
    //如果有转发 原创就不需要配图不用缓存 只显示转发的
    //定义一个计算属性,用于返回原创或者转发配图的URL数组
    var pictureURLS: [NSURL]?{
        return retweeted_status != nil ? retweeted_status?.storePicURLS:storePicURLS
    }

    
    
    var user: User?
    //加载微博数据
    class func loadStatuses(since_id :Int,max_id:Int,finished:(models:[Statuses]?,error:NSError?)->()){
        let path = "2/statuses/friends_timeline.json"
        
        guard UserAccount.account?.access_token?.characters.count != 0 else{
            return;
        }
        var params = ["access_token":UserAccount.account!.access_token!]
        
        //下拉刷新
        if since_id > 0 {
        params["since_id"] = "\(since_id)"
            
        }
        
        //上拉刷新
        if max_id > 0 {
            params["max_id"] = "\(max_id)"
        }
        guard params.count != 0 else{
            return
        }
        
        print(params)
        NetWorkTools.shareNetWorkTools().GET(path, parameters: params as? AnyObject , progress: { (progress:NSProgress) in

            }, success: { (task:NSURLSessionDataTask, result:AnyObject?) in
                
                let models = dict2Model(result!["statuses"]! as! [[String:AnyObject]])
                            //缓存微博配图
                            cacheStatusImages(models, finished: { (models, error) in
                            finished(models: models, error: nil)//如果没有数据也
                
                                
                            })
                
                
        }) { (task:NSURLSessionDataTask?, error:NSError) in
            
            finished(models: nil, error: error)

        }
        
        

        
        
    }
    
    class func cacheStatusImages(list:[Statuses],finished:(models:[Statuses]?,error:NSError?)->()){
    
        if  list.count <= 0 {//如果没有数据也回调一次
            finished(models: list, error: nil)//如果没有数据也
            return 
        }

        //创建一个组
        let group = dispatch_group_create()
        
        //缓存图片
        for status in list{
            if status.storePicURLS == nil {//如果没有配图 . 没有配图就不会创建对象
                continue
            }
            guard let _ = status.pictureURLS else {//判断是否为nil 如果条件满足执行else语句
                print("status.storePicURLS?.count")
                continue
            }
            
            for url in status.pictureURLS! {//缓存图片
                //将当前的下载操作添加到组中
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue:0), progress: { (Int, progress) in
                    
                    
                    }, completed: { (image:UIImage!, error:NSError!, SDImageCacheType, success:Bool, url:NSURL!) in
                      //离开当前组
                       dispatch_group_leave(group)
//                        print("OK")
                })
            }

            
        }
        //2.当所有图片下载完毕后再通过闭包通知调用者
        dispatch_group_notify(group, dispatch_get_main_queue()) { 
            //能够来到这个地方一定是所有图片都下载完毕
            finished(models: list, error: nil)
//            print("OVer")

        }
    
    }
    
    class func dict2Model(list:[[String:AnyObject]])->[Statuses]{
        
        var models = [Statuses]()
        for dic in list {
            models.append(Statuses(dict: dic))
        }
        return models
        
    }
    //字典转模型
    
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        super.setValue(value, forKey: key)
//        print("value=  \(value) ,key=  \( key)")
        if  key == "user" {//根据userkey字典创建模型
          user =  User.init(dic: value! as! [String : AnyObject])
        }
        
        if "retweeted_status" == key{
            retweeted_status = Statuses(dict:value as![String:AnyObject])
            
        }
        //判断是否是转发微博 如果是处理
        
    }
    
    
    //kvc赋值的时候肯定会走这个方法
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print( "\(key):\(value)")
        return
    }
    
    
    var properties = ["created_at","id","text","source","pic_urls"]
    
    override var description: String{
        let dict = dictionaryWithValuesForKeys(properties)
        return"\(dict)"
        
    }
}
